package controllers

import (
	"net/http"
	"encoding/json"
	"git.oschina.net/YPTArch/processcache/sys/logs"
	"git.oschina.net/YPTArch/processcache/models"
	"errors"
)

//验证header中需要取的值
const (
	TOKEN = "Token"
	UID = "Uid"
)


//redis 访问延时
func Validate(w http.ResponseWriter, r *http.Request)   {
	logs.Logger.Debug("success in validate")

	var result models.Result

	err := validateHandler(r)
	if err != nil {
		result = models.Result{Code: models.Unauthorized, Msg: "验证处理失败！", Data: err.Error()}
	} else {
		result = models.Result{Code: models.Ok, Msg: "验证成功！", Data: ""}
	}

	re, err := json.Marshal(result)
	if err != nil {
		logs.Logger.Error(err.Error())
		w.Write([]byte(models.ServerErr))
	}

	w.Write(re)
}

//验证处理
func validateHandler(r *http.Request) (error)  {

	redisToken, err := validateUser(r)
	if err != nil {
		return err
	}

	err = models.Delay(USER+redisToken.UserId, redisToken.AccessExpiresIn)
	if err != nil {
		return err
	}

	return nil
}

func validateUser(r *http.Request) (*models.RedisToken, error)  {

	token, err := getHeaderValue(r, TOKEN)
	if err != nil {
		return nil, err
	}
	if token == "" {
		return nil, errors.New("token为空")
	}

	uid, err := getHeaderValue(r, UID)
	if err != nil {
		return nil, err
	}
	if uid == "" {
		return nil, errors.New("uid为空")
	}


	//从redis中获取结构
	redisToken, err := models.GetTokenRequest(USER+uid)
	if err != nil {
		return nil, err
	}

	//判断用户未登录
	if redisToken == nil {
		return nil, errors.New("用户未登录")
	}


	//查询出的token和传递的token不一致，则为伪造用户
	if redisToken.Access  != token {
		return nil, errors.New("用户信息不一致")
	}

	return redisToken, nil
}

//从header 中获取token
func getHeaderValue(r *http.Request, valueName string) (string, error)   {

	//header 中不存在
	if _, ok := r.Header[valueName]; !ok {
		return "", nil
	}

	var value string
	//存在但是数量不是一个，那么返回错误
	if len(r.Header[valueName]) != 1 {
		return "", errors.New("验证登录token数量不正确！")
	}else {
		value = r.Header[valueName][0]
	}

	return value, nil
}

